# coding: utf-8
from pathlib import Path
from typing import Union

import httpx
from PIL import Image, ImageQt
from PySide6.QtGui import QImage
from moviepy import VideoFileClip


def get_file_size(file_path: Union[str, Path]) -> int:
    """
    获取文件大小
    :param file_path:
    :return:
    """
    if isinstance(file_path, str):
        file_path = Path(file_path)
    if not file_path.exists():
        return 0
    return file_path.stat().st_size


def speed_to_str(speed: Union[float, int]) -> str:
    if speed < 1024:
        return f'{speed:.2f} B'
    elif speed < 1024 ** 2:
        return f'{speed / 1024:.2f} KB'
    elif speed < 1024 ** 3:
        return f'{speed / 1024 ** 2:.2f} MB'
    else:
        return f'{speed / 1024 ** 3:.2f} GB'


def get_video_cover(file_path: Union[str, Path], t: Union[float, int] = None) -> QImage:
    """
    获取视频封面图片
    :param t: 截取时间点  (秒)
    :param file_path: 视频文件路径
    :return:
    """
    clip = VideoFileClip(file_path)
    if t is None:
        t = clip.duration / 4  # 取视频的中间时刻
    cover = clip.get_frame(t)
    clip.close()
    image = Image.fromarray(cover)
    return ImageQt.toqimage(image)
